package cn.tedu.net;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ChatPrivateClient {

    private Socket socket;

    public ChatPrivateClient()throws Exception{
        socket = new Socket("localhost",8080);
        // 启动服务助手，用以接收服务返回的数据
        ServerHandler serverHandler = new ServerHandler();
        serverHandler.start();

        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        PrintWriter pw = new PrintWriter(bw,true);

        Scanner scanner = new Scanner(System.in);
        // 先设置名字
        String name = null;
        do {
            System.out.println("请输入名字：");
            name=scanner.nextLine();
            pw.println("setName"+name);
        }
        while(name.trim().isEmpty());

        // 发送普通正文
        while(true){
            System.out.println("请输入内容：");
            String s = scanner.nextLine();
            if("exit".equals(s)){
                break;
            }
            pw.println(s);
        }
        pw.close();
    }


    // 用来接收服务端发回来的消息
    class ServerHandler extends Thread{
        @Override
        public void run() {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br =  new BufferedReader(isr);
                String line = null;
                while((line=br.readLine())!=null){
                    System.out.println(line);
                }
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)throws Exception {
        ChatPrivateClient chatClient =  new ChatPrivateClient();
    }
}
